import json
import uvicorn
from threading import Thread
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import JSONResponse

from src.logger import Logger
from src.user_data import UserData


class Server:
    def __init__(self, conf: UserData, logger: Logger):
        self.__logger = logger
        self.__conf = conf
        self.__ini = self.__conf.iniCls
        # 内部参数
        self.__app = FastAPI()
        self.__bind_event()

    def __bind_event(self):
        """绑定接收请求函数"""
        @self.__app.get('/insert')
        @self.__app.post('/insert')
        async def func(request: Request):
            try:
                params = {}
                if request.method == "GET":
                    params = request.query_params
                elif request.method == "POST":
                    params = json.loads(await request.body())
                # 身份验证
                if params.get("token") != self.__ini.server_token:
                    return JSONResponse({"code": 403, "msg": "身份未验证!"}, status_code=403)
                # 添加文本到logger中
                raw_text: str = params.get("raw_text", "")
                if raw_text:
                    self.__logger.add_log(raw_text)
                return JSONResponse({"code": 200, "msg": "OK!"})
            except Exception:
                return JSONResponse({"code": 500, "msg": "数据格式不合法！"})

    def start(self):
        # 端口正确设置时才启动服务
        if not self.__ini.server_port:
            return

        def run():
            uvicorn.run(app=self.__app, host="0.0.0.0", port=self.__ini.server_port, log_level="error", use_colors=True)

        Thread(target=run, daemon=True).start()
        self.__logger.add_log(f"[GLF机器人] API服务成功启用！地址: http://0.0.0.0:{self.__ini.server_port}")

    def reload(self):
        self.__ini = self.__conf.iniCls
